package cn.wgx.module.mind.service;

import cn.wgx.common.entity.mind.MindBeat;
import cn.wgx.common.entity.mind.MindBeatContent;
import cn.wgx.module.mind.entity.mapper.BeatMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

@Service
public class BeatService extends BaseMindService<BeatMapper, MindBeat> {

    @Autowired
    private BeatContentService beatContentService;
    @Autowired
    private LinkService linkService;

    @Override
    @Transactional()
    public boolean save(MindBeat mindBeat){
        boolean save = super.save(mindBeat);
        if(save)ini(mindBeat);
        return save;
    }

    @Override
    @Transactional()
    public boolean saveBatch(Collection<MindBeat> mindBeat){
        boolean save = super.saveBatch(mindBeat);
        ini(mindBeat);
        return save;
    }

    @Transactional()
    public boolean removeById(Serializable id){
        boolean b = super.removeById(id);
        destroy(id);
        return b;
    }

    @Transactional()
    public boolean removeByIds(Collection<? extends Serializable> ids){
        boolean b = super.removeByIds(ids);
        destroy(ids);
        return b;
    }

    @Transactional(readOnly = true)
    public List<MindBeat> getListByProId(Integer pro_id){
        MindBeat mindBeat = new MindBeat();
        mindBeat.setPro_id(pro_id);
        List<MindBeat> mindBeats = baseMapper.selectList(new QueryWrapper<>(mindBeat).orderBy(true, true, "sort"));
        return mindBeats;
    }

    private void ini(Collection<MindBeat> mindBeats){
        for(MindBeat mindBeat: mindBeats){
            ini(mindBeat);
        }
    }
    //初始化节点正文部分
    private void ini(MindBeat mindBeat){
        if(mindBeat != null && mindBeat.getBeat_id() != null){
            MindBeatContent mindBeatContent = new MindBeatContent();
            mindBeatContent.setBeat_id(mindBeat.getBeat_id());
            mindBeatContent.setPro_id(mindBeat.getPro_id());
            mindBeatContent.setContent("");
            beatContentService.save(mindBeatContent);
        }
    }


    private void destroy(Collection<? extends Serializable> mindBeats){
        beatContentService.removeByIds(mindBeats);
        linkService.removeByBeatId(mindBeats);
    }


    private void destroy(Serializable id){
        beatContentService.removeById(id);
        linkService.removeByBeatId(id);
    }
}
